package com.dy.mongo.service;

import com.dy.mongo.document.PersonImage;
import com.dy.mongo.document.PersonVideo;
import com.dy.mongo.document.PersonText;
import com.dy.mongo.repository.PersonImageRepository;
import com.dy.mongo.repository.PersonVideoRepository;
import com.dy.mongo.repository.PersonTextRepository;
import lombok.RequiredArgsConstructor;
import org.bson.Document;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLConnection;

@Service
@RequiredArgsConstructor
public class MediaService {
    private final GridFsTemplate gridFsTemplate;
    private final PersonImageRepository imageRepo;
    private final PersonVideoRepository videoRepo;
    private final PersonTextRepository textRepo;

    public void uploadSingle(Long csvId, String type, String title, String description, MultipartFile file) throws IOException {
        switch (type) {
            case "image" -> {
                String mime = URLConnection.guessContentTypeFromName(file.getOriginalFilename());
                if (mime == null) mime = MediaType.IMAGE_JPEG_VALUE;
                String fileId = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), mime,
                        new Document("csvId", csvId)).toHexString();
                imageRepo.save(new PersonImage(null, csvId, title, fileId, description));
            }
            case "video" -> {
                String mime = URLConnection.guessContentTypeFromName(file.getOriginalFilename());
                if (mime == null) mime = MediaType.APPLICATION_OCTET_STREAM_VALUE;
                String fileId = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), mime,
                        new Document("csvId", csvId)).toHexString();
                videoRepo.save(new PersonVideo(null, csvId, title, fileId, null, description));
            }
            case "text" -> {
                String content = new String(file.getBytes());
                textRepo.save(new PersonText(null, csvId, title, content));
            }
            default -> throw new IllegalArgumentException("type 必须是 image / video / text");
        }
    }
} 